package db

import (
	"database/sql"
	"errors"
	"time"
)

type User struct {
	ID         uint64    `json:"id,string" db:"id"`
	UserID     uint64    `json:"userId,string" db:"user_id"`
	Username   string    `db:"username"`
	Password   string    `db:"password"`
	Email      string    `db:"email"`
	Gender     uint8     `db:"gender"`
	CreateTime time.Time `db:"create_time"`
	UpdateTime time.Time `db:"update_time"`
}

// 插入数据到数据库
func NewUser(u *User) (err error) {
	_, err = DB.Exec("insert into `user`(user_id , username , password ) values(? , ? , ?) ", u.UserID, u.Username, u.Password)
	return
}

func CountByUsername(un string) (int, error) {
	var count int
	err := DB.QueryRow("select count(1) from `user` where username = ?", un).Scan(&count)

	return count, err
}

func GetByUsername(un string) (*User, error) {

	u := &User{}
	err := DB.Get(u, "select * from `user` where username = ? ", un)
	return u, err
}

func GetByUserId(uid uint64) (u *User, err error) {

	u = new(User)
	err = DB.Get(u, "select * from `user` where user_id = ?", uid)
	if errors.Is(err, sql.ErrNoRows) {
		return nil, nil
	}
	return
}
